package com.tool_stdy.ConcurrencyModel.WorkMastser;

import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

import com.google.common.collect.Maps;

/**
 * Created by yan_li on 2016/11/11.
 */
public class Master {

    //1 有一个盛放任务的容器
    private Queue<Task> workQueue = new ConcurrentLinkedQueue<Task>();
    //2 需要有一个盛放worker的集合
    private Map<String, Thread> workers = Maps.newHashMap();
    //3 需要有一个盛放每一个worker执行任务的结果集合
    private Map<String, Task> resultMap = new ConcurrentHashMap<String, Task>();

    //4 构造方法
    public Master(Worker worker, int countWorker) {
        worker.setWorkQueue(this.workQueue);
        worker.setResultMap(this.resultMap);
        for (int i = 0; i < countWorker; i++) {
            workers.put(Integer.toString(i), new Thread(worker));
        }
    }

    //5 需要一个提交任务的方法
    public void submitTask(Task task) {
        this.workQueue.add(task);
    }

    //6 需要有一个执行的方法，启动所有的worker方法去执行任务
    public void execute() {
        for (Map.Entry<String, Thread> en : workers.entrySet()) {
            en.getValue().start();
        }
    }

    //7 判断是否运行结束的方法
    public boolean isComplete() {
        for(Map.Entry<String, Thread> me : workers.entrySet()){
            if(me.getValue().getState() != Thread.State.TERMINATED){
                return false;
            }
        }
        return true;
    }

    //8 计算结果方法
    public int getResult() {
        int priceResult = 0;
        for (Map.Entry<String, Task> me : resultMap.entrySet()) {
            priceResult += me.getValue().getPrice();
        }
        return priceResult;
    }
}
